package controller;

import java.util.List;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import model.Station;

import org.primefaces.event.RowEditEvent;

import service.StationService;

@ManagedBean
@SessionScoped
public class StationController {
	@EJB
	private StationService stationService;
  
	private List<Station> allStations = null;

	private Station station = new Station();
	
	public Station getStation() {
		return station;
	}
	
	public List<Station> getAllStations() {
		if (allStations == null) {
			allStations = stationService.findAll();
			return allStations;
		} else {
			return allStations;
		}
	}
	
	public void onEdit(RowEditEvent event) {  
		Station editStation = (Station) event.getObject();
		String result = stationService.update(editStation);
		allStations = stationService.findAll();
		FacesMessage msg = new FacesMessage(result);  
        FacesContext.getCurrentInstance().addMessage(null, msg);  
    }  
      
    public void deleteStation(Station station) {  
    	stationService.delete(station);
    	allStations = stationService.findAll();
    	FacesMessage msg = new FacesMessage("ok");  
        FacesContext.getCurrentInstance().addMessage(null, msg); 
    }  
    
    public void createStation() {  
    	String result = stationService.save(this.station);
    	this.station = new Station();
    	allStations = stationService.findAll();
    	FacesMessage msg = new FacesMessage(result);  
        FacesContext.getCurrentInstance().addMessage(null, msg);  
    }  

}
